shell - 获取文件中的特定字符并交换列

标签 shell awk

我正在尝试获取每一行的第 20 个字符,如果它的 b 则将最后两列与其他值交换,如果它的 B 则最后一列和最后一列应该交换列的值,如下所示。

输入示例:

1234567891011121314b abcd erfg ijkl 12114353 blabla
1234567891011121314Babcd erfg ijkl 12114353 blabla

预期输出示例:

1234567891011121314b abcd erfg ijkl blabla 12114353
123456789101112131Babcd erfg blabla 12114353 ijkl

我尝试了以下代码:

while read value
do
    echo "$value" | cut -c20
done < "file"

我也尝试过使用 awksubstr 但也无法在其中进行太多操作。

实际文件与上面显示的示例相同;请指导我。

最佳答案

根据您显示的示例,您能否尝试以下操作。用 GNU awk 编写和测试。

awk '
{
  val=substr($0,20,1)
}
val=="b"{
  temp=$(NF-1)
  $(NF-1)=$NF
  $NF=temp
  temp=""
}
val=="B"{
  temp=$(NF-2)
  $(NF-2)=$NF
  $NF=temp
  temp=""
}
1' Input_file

说明: 为以上添加详细说明。

awk '                   ##Starting awk program from here.
{
  val=substr($0,20,1)   ##getting 20th character value here.
}
val=="b"{               ##Checking condition if val is b then do following.
  temp=$(NF-1)          ##Creating temp with 2nd last field value here.
  $(NF-1)=$NF           ##Setting last field value to 2nd last field here.
  $NF=temp              ##Again setting last field as temp.
  temp=""               ##Nullifying temp here.
}
val=="B"{               ##Checking condition if val is B then do following.
  temp=$(NF-2)          ##Creating temp which has 3rd last field value here.
  $(NF-2)=$NF           ##Setting 3rd last field value to last field here.
  $NF=temp              ##Again setting last field as temp.
  temp=""               ##Nullifying temp here.
}
1                       ##Printing current line here.
' Input_file            ##Mentioning Input_file name here.

关于shell - 获取文件中的特定字符并交换列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66277527/

相关文章:

bash - 如何按字母顺序对主列进行排序,然后按数字顺序对辅助列进行排序?

bash - awk 无法忽略 "++"

variables - 删除awk中的一个变量

将行转列的 Linux 脚本

awk - 将 awk 命令存储在 bash 脚本的变量中

shell - 如何使用今天的日期重命名现有文件

linux - append 到文件时如何避免竞争条件?

bash从两个文件中获取信息

linux - Sqlite:比较两个数据库并更新旧的 - Linux

linux - 查找新文件夹的索引