awk:保留多个字段分隔符 [英] awk: Preserve multiple field separators

查看:347
本文介绍了awk:保留多个字段分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用awk使用两个不同的字段分隔符交换文件名中的字段. 我想知道是否可以将两个分隔符'/'和'_'保留在输出中的正确位置.

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.

示例:

我要更改此内容

/path/to/示例文件 _123.txt

/path/to/example_file_123.txt

对此:

/path/to/文件示例 _123.txt

/path/to/file_example_123.txt

我尝试过:

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

但是我明白了:

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

处理多个分隔符时,有没有一种方法可以在awk中保留正确的原始字段分隔符?

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

推荐答案

$ 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

这篇关于awk:保留多个字段分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆