awk: Preserve multiple field separators

大城市里の小女人 提交于 2019-12-24 06:45:56

问题


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


来源:https://stackoverflow.com/questions/30197655/awk-preserve-multiple-field-separators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!