简体   繁体   English

awk:保留多个字段分隔符

[英]awk: Preserve multiple field separators

I'm using awk to swap fields in a filename using two different field separators. 我正在使用awk使用两个不同的字段分隔符交换文件名中的字段。 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 / path / to / example_file _123.txt

into this: 到这个:

/path/to/ file_example _123.txt / 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? 处理多个分隔符时,有没有办法在awk中保留正确的原始字段分隔符?

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. 您可以随时使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM