awk: Preserve multiple field separators

2019-07-26 16:30发布

问题:

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?

回答1:

$ 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


回答2:

Here is one solution:

awk -F/ '{n=split($NF,a,"_");b=a[1];a[1]=a[2];a[2]=b;$NF=a[1];for (i=2;i<=n;i++) $NF=$NF"_"a[i]}1' OFS=/ file
/path/to/file_example_123.txt


回答3:

You can always use Perl.

Given:

$ echo $e
/path/to/example_file_123.txt

Then:

$ echo $e | perl -ple 's/([^_\/]+)_([^_\/]+)/\2_\1/'
/path/to/file_example_123.txt