Search code examples
bashawkseparator

awk: Preserve multiple field separators


I'm using awk to swap fields in a filename using two different field separators. I want to know if it's possible to preserve both separators, '/' and '_', in the correct positions in the output.

Example:

I want to change this:

/path/to/example_file_123.txt

into this:

/path/to/file_example_123.txt

I've tried:

awk -F "[/_]" '{ t=$3; $3=$4; $4=t;print}' file.txt

but the field separators are missing from the output:

path to file example 123.txt

I've tried preserving the field separators:

awk -F "[/_]" '{t=$3; $3=$4; $4=t; OFS=FS; print}' file.txt

but I get this:

[/_]path[/_]to[/_]file[/_]example[/_]123.txt

Is there a way of preserving the correct original field separator in awk when you're dealing multiple separators?


Solution

  • $ cat /tmp/1
    /path/to/example_file_123.txt
    /path/to/example_file_345.txt
    
    $ awk -F'_' '{split($1,a,".*/"); gsub(a[2],"",$1);print $1$2"_"a[2]"_"$3}' /tmp/1
    /path/to/file_example_123.txt
    /path/to/file_example_345.txt