0

i have in test.idx many text and i will all lines with:

# alt: Spanish
# alt: German
# alt: Englisch

my script:

#!/bin/bash
results=$(cat /home/test.idx | grep "# alt:" | awk '{print $3}')
echo "$results"

output is among themselves:

Spanish
German
English

how can output one after the other? :

Spanish German English

Regards

2 Answers2

0

One way, pipe into paste:

awk '{print $3}' | paste -s -

Another, use printf instead of print:

awk '{printf "%s ", $3} END { print "" }'
jas
  • 10,715
  • 2
  • 30
  • 41
0
$ awk '/# alt:/{printf "%s%s", (NR>1 ? OFS : ""), $NF} END{print ""}' file
Spanish German Englisch

and in response to your comment under @jas's answer:

$ awk -v OFS=', ' '/# alt:/{printf "%s%s", (NR>1 ? OFS : ""), $NF} END{print ""}' file
Spanish, German, Englisch

This only works for one-word languages, if you have to handle "Ancient Greek" for example then you'd need a slightly different solution, e.g.:

$ cat file
# alt: Spanish
# alt: Ancient Greek
# alt: Englisch
# alt: Upper Sorbian

$ awk -v OFS=', ' 'sub(/^# alt: */,""){printf "%s%s", (NR>1 ? OFS : ""), $0} END{print ""}' file
Spanish, Ancient Greek, Englisch, Upper Sorbian
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • hmm, dont work, results=$(cat /home/test.idx | grep "# alt:" | awk -v OFS=', ' '/# alt:/{printf "%s%s", (NR>1 ? OFS : ""), $NF} END{print ""}') result is ", English" and with results=$(cat /home/test.idx | awk -v OFS=', ' '/# alt:/{printf "%s%s", (NR>1 ? OFS : ""), $NF} END{print ""}') is same result ", English" – huburt achmet Dec 02 '18 at 15:55
  • with comand awk -v OFS=', ' '/# alt:/{printf "%s%s", (NR>1 ? OFS : ""), $NF} END{print ""}' /home/test.idx is output , English – huburt achmet Dec 02 '18 at 15:59
  • its a problem that another text between is it? wtih only # alt: ... in all lines working this – huburt achmet Dec 02 '18 at 16:06
  • See https://stackoverflow.com/a/45772568/1745001 for more information on this issue. – Ed Morton Dec 02 '18 at 16:23