Skip to main content
2 of 4
Spelling

The following function will use only Bash built-ins ( in case that you want to use Bash ) to do what you want:

foo () 
{ 
    while IFS='|' read -r pre name suf; do
        l="$pre|${name#* },${name% *}|$suf";
        printf '%s\n' "$l";
    done < "$1"
}

The IFS variable is set to | and 'read' reads every line at a time from "$1" ( your file ) and divides it into three parts, $pre $name and $suf, according to the IFS value.

$pre value is set to be the field before the name, $name is set to be the name itself which you want to swap ( the second field ) and $suf is the rest of the line.

I use parameter expansion ( search for parameter expansion in man bash ) to split the $name field.

"${name#* }" will cut the first name, leaving us with the last name.

"${name% *}" will cut the last name, leaving us with the first name.

Usage: foo [/path/to/file.txt]

Sample output:

nylon100@~$ cat>file.txt
123|first1 last1|foo|bar|date|baz
456|first2 last2|foo|bar|date|baz
789|first3 last3|foo|bar|date|baz

nylon100@~$ foo file.txt
123|last1,first1|foo|bar|date|baz
456|last2,first2|foo|bar|date|baz
789|last3,first3|foo|bar|date|baz