简体   繁体   中英

Sorting a list in bash 1

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

One way, pipe into paste:

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

Another, use printf instead of print:

awk '{printf "%s ", $3} END { print "" }'
$ 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, eg:

$ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM