I have a file with the header (first line) with a variable length; and it comes as:



"One"|"Two"|"Three"|...|"One Hundred"

and want to get do a loop that transforms it into a new file:

"Hello One!"
"Hello Two!"
"Hello Three! ..."
"Hello One Hundred!"

What should I do? Use awk? sed?

I couldn't find a solution without fixing the size.

My OS is Linux-RedHat-RHEL-6.

  • Are the double quotes part of your actual data? – glenn jackman Sep 10 '15 at 16:18
  • Yes, but they as well could come without it. – UberM Sep 10 '15 at 16:21
  • Need there be a special solution for ...? The second example include it inside the string. – jofel Sep 10 '15 at 16:35
  • ... it just means that it continues to "Four"|"Five"... – UberM Sep 10 '15 at 16:37

bash: read the pipe-separated words into an array

IFS='|' read -ra words < <(head -n 1 file)
printf "Hello %s!\n" "${words[@]}"

awk: iterate over the words in the line.

awk -F'|' 'NR == 1 { for (i=1; i<=NF; i++) print "Hello " $i "!"; exit}' file

and a sed:

sed -e 2Q -e 's/\([^|]\+\)/Hello \1!/g' -e 's/[|]/\n/g' file
  • Thanks it worked, will accept it later cause I still can't :D – UberM Sep 10 '15 at 16:23
  • Why not use head with the awk approach as well to keep things simple? – terdon Sep 10 '15 at 16:25
  • sed example does not do the quotation correctly. It need to be [^|"] in the first expression. – jofel Sep 10 '15 at 16:38

Here a simple solution with two sed calls (assumes every line is quoted):

sed -n '1s#"|"#"\n"#gp' file | sed 's#"\(.*\)"#"Hello \1!"#'

First sed command replaces "|" with newlines. Second adds the texts and exclamation mark.

If there are no | inside the data and surrounding " are optional, you can also use (shoud be faster):

head -1 file | tr \| \\n | sed 's#"\?\(.*\)"\?#"Hello \1!"#'
  • 1
    This actually matches the desired output in the OP post though you could do without the first sed (and faster): tr \| \\n | sed... – don_crissti Sep 10 '15 at 16:44
  • @don_crissti yes, but your suggestion fails if | is inside the string. My solution at least handle some of these special cases. If there are no | inside the strings, why is there the quotation? – jofel Sep 10 '15 at 16:48
  • @don_crissti ok, I extend my answer. – jofel Sep 10 '15 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.