我正在尝试获取每一行的第 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"
我也尝试过使用 awk
的 substr
但也无法在其中进行太多操作。
实际文件与上面显示的示例相同;请指导我。
最佳答案
根据您显示的示例,您能否尝试以下操作。用 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/