Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

awk, sed, for in bash: Print "Hello" + Name

I have a list.csv with the following content:

"date";"Mr. Green Tree"
"date";"Mr. Red Apple"
"date";"Mr. Blue Car"

I use awk + sed to get the following output:

awk -F ";" '{print $2 }' list.csv | sed 's/"//g'

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Mr Green Tree
Mr Red Apple
Mr Blue Car 

Now I want to use the same command in a for loop and add the string "Hello"

script.sh

get_name () {
    name=$(awk -F ";" '{print $2 }' list.csv | sed 's/"//g')
    for string in $name; do
        echo "Hello" $string
    done
}

get_name

Output when I execute script.sh:

Hello Mr
Hello Green
Hello Tree
Hello Mr
Hello Red
Hello Apple 
Hello Mr
Hello Blue
Hello Car 

Expected Output:

Hello Mr Green Tree
Hello Mr Red Apple
Hello Mr Blue Car

>Solution :

Try:

awk -F ";" '{print $2 }' list.csv | sed 's/"//g' | while read -r line || [[ -n $line ]]; do 
    printf "Hello %s\n" "$line"
done 

If you know the input will be \n terminated:

awk -F ";" '{print $2 }' list.csv | sed 's/"//g' | while read -r line; do 
    printf "Hello %s\n" "$line"
done 

Bash loop from here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading