unix - cut command --complement flag 在 AWK 中等效于复杂参数
问题描述
这个问题是对现有问题的跟进
不要将此标记为重复,因为问题的期望完全不同
我正在尝试编写一个完全执行以下操作的 AWK 命令
命令 1:
cut --complement -c $IGNORE_RANGE file.txt > tmp
命令 2:
cut --complement -d, -f$IGNORE_RANGE $report > tmp
$IGNORE_RANGE 可以是任何值,例如 1-5,6 或 1,3,5 1,3-5 等
我不能使用 cut,因为我在 AIX 中并且 AIX 不支持 --complement,有没有办法使用 AWK 命令来实现这一点
命令 1 的示例:
文件.txt
abcdefg
1234567
输出
cut --complement -c 1-5,6 file.txt > tmp
g
7
cut --complement -c 1,3,5 file.txt > tmp
bdfg
2467
cut --complement -c 1,3-5 file.txt > tmp
bfg
267
命令 2 的示例:
文件.txt
data1,data2,data3,data4,data5,data6,data7
输出
cut --complement -d, -f 1-5,6 file.txt > tmp
data7
cut --complement -d, -f 1,3,5 file.txt > tmp
data2,data4,data6,data7
cut --complement -d, -f 1,3-5 file.txt > tmp
data2,data6,data7
解决方案
1st solution for OP's position number problem: Could you please try following, a generic solution based on provided samples written and tested in GNU awk
and needed GNU awk
to be executed. One could give ranges or individual position number separated by ,
in awk
's ignore_pos
variable.
awk -v FS= -v ignore_pos="1-5,6" '
BEGIN{
num=split(ignore_pos,array1,",")
for(i=1;i<=num;i++){
if(array1[i]~/-/){
split(array1[i],array2,"-")
for(j=array2[1];j<=array2[2];j++){
ignore[j]
}
}
else{
ignore[array1[i]]
}
}
}
{
for(i=1;i<=NF;i++){
if(!(i in ignore)){ val=val $i }
}
$0=val
val=""
}
1
' Input_file
2nd solution for OP's field number problem: When one wants to ignore fields we could use this solution then(OP's command2 examples taken here to run this). As per OP's samples ,
comma has been made as field separator for Input_file here.
awk -v ignore_field="1-5,6" '
BEGIN{
FS=OFS=","
num=split(ignore_pos,array1,",")
for(i=1;i<=num;i++){
if(array1[i]~/-/){
split(array1[i],array2,"-")
for(j=array2[1];j<=array2[2];j++){
ignoreFields[j]
}
}
else{
ignoreFields[array1[i]]
}
}
}
{
for(i=1;i<=NF;i++){
val=""
if(!(i in ignoreFields)){ val=(val?val OFS:"")$i }
}
$0=val
}
1
' Input_file
推荐阅读
- ios - Azure Web App - 当您选择运行时堆栈作为 Node.js 时,为什么它只允许您选择 Linux 作为操作系统?
- python - pandas 如何神奇地选择列来应用布尔索引?
- javascript - 删除数组中的所有重复项和未定义项。Ramda.js
- c# - 我的 Unity 项目中出现了 Microsoft (R) Visual C# 编译器错误
- python - 如何使用 google-api-client 创建实例?
- ios - swift segue new viewcontroller 在后台加载其他任务时卡住
- firebase - Flutter Firebase 我将如何从快照中获取特定数据
- html - 为什么 flexbox 在包装元素后不收缩以适应?
- dll - 无法在 .NET Core 3 中卸载 DLL
- python - 蜘蛛错误处理 - Python Web Scraping 错误