简体   繁体   中英

Awk formatting by field separators

To start I would prefer not using sed to just remove that last part; the reason is because the file has a lot of variables that I would have to do this with.

echo $new

it will display

Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text. Metro Filer:

So it's one lone line of text that I need to break, get rid of the Metro Filer: as generically as possible so I can use it for all my other variables (100+ other variables).

Also, where it says It has a lot more text means there is a lot more text there, I just don't want to make a massive string. There is only a colon at the beginning and the end.

What I would like it to look like is

Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text.

I tried a couple things with awk -F ":" and just couldn't seem to include Jack: , so any help would be great!

Awk

$ echo "$new" | awk '{a=$1;for(i=2;i<NF-1;++i)a=a FS $i;print a}'
Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text.

It assigns the first field to a , then appends a space and the next field for all but the last two fields, and finally prints the variable.

More readable:

{
    string = $1
    for (i = 2; i < NF-1; ++i)
        string = string FS $i
    print string
}

rev and cut

$ echo "$new" | rev | cut -d ' ' -f 3- | rev
Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text.

This reverses the output, then extracts all space separated fields starting with the third, and reverses that again.

Parameter expansion

$ echo "${new% * *}"
Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text.

This says: remove from the end "space whatever space whatever", in a non-greedy fashion.

Sed

This isn't any more complicated with respect to having many variables than any of the other methods.

$ echo "$new" | sed 's/ [^ ]* [^ ]*$//'
Jack: Grow up far away. He loves food Hotdogs, Hamburgers, and steak. It has a lot more text.

This removes a space and two non-space groups, separated by another space, from the end of the string.

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