简体   繁体   中英

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?

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

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
$ 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

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