Unix - 需要剪切一个有多个空格作为分隔符的文件 - awk或cut?

vis*_*akh 10 unix awk cut delimiter

我需要从Unix中的文本文件中获取记录.分隔符是多个空格.例如:

2U2133   1239  
1290fsdsf   3234
Run Code Online (Sandbox Code Playgroud)

由此,我需要提取

1239  
3234
Run Code Online (Sandbox Code Playgroud)

所有记录的分隔符将始终为3个空格.

我需要在unix脚本(.scr)中执行此操作,并将输出写入另一个文件或将其用作do-while循环的输入.我试过以下:

while read readline  
do  
        read_int=`echo "$readline"`  
        cnt_exc=`grep "$read_int" ${Directory path}/file1.txt| wc -l`  
if [ $cnt_exc -gt 0 ]  
then  
  int_1=0  
else  
  int_2=0  
fi  
done < awk -F'  ' '{ print $2 }' ${Directoty path}/test_file.txt  
Run Code Online (Sandbox Code Playgroud)

test_file.txt是输入文件,file1.txt是查找文件.但上面的方法不起作用,并在awk -F附近给我语法错误

我尝试将输出写入文件.以下在命令行中工作:

more test_file.txt | awk -F'   ' '{ print $2 }' > output.txt
Run Code Online (Sandbox Code Playgroud)

这是在命令行中将记录写入output.txt.但是同样的命令在unix脚本中不起作用(它是.scr文件)

请让我知道我哪里出错了,以及如何解决这个问题.

谢谢,
维萨克

wlf*_*wlf 23

cat <file_name> | tr -s ' ' | cut -d ' ' -f 2
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 11

这取决于cut您机器上的版本或实现.有些版本通常支持一个选项,-i意思是"忽略空白字段",或者等效地允许字段之间有多个分隔符.如果支持,请使用:

cut -i -d' ' -f 2 data.file
Run Code Online (Sandbox Code Playgroud)

如果不是(并且它不是通用的 - 甚至可能不普及,因为GNU和MacOS X都没有选项),那么使用awk更好,更便携.

但是,您需要将输出传递awk到循环中:

awk -F' ' '{print $2}' ${Directory_path}/test_file.txt |
while read readline  
do  
    read_int=`echo "$readline"`  
    cnt_exc=`grep "$read_int" ${Directory_path}/file1.txt| wc -l`  
    if [ $cnt_exc -gt 0 ]  
    then int_1=0  
    else int_2=0
    fi  
done
Run Code Online (Sandbox Code Playgroud)

唯一剩下的问题是while循环是否在子shell中,因此不会修改主shell脚本变量,只是它自己的那些变量的副本.

使用bash,您可以使用进程替换:

while read readline  
do  
    read_int=`echo "$readline"`  
    cnt_exc=`grep "$read_int" ${Directory_path}/file1.txt| wc -l`  
    if [ $cnt_exc -gt 0 ]  
    then int_1=0  
    else int_2=0
    fi  
done < <(awk -F' ' '{print $2}' ${Directory_path}/test_file.txt)
Run Code Online (Sandbox Code Playgroud)

这会将while循环保留在当前shell中,但会将命令的输出安排为从文件中显示.

空白${Directory path}通常不合法 - 除非它是我错过的另一个Bash功能; 你Directoty在一个地方也有一个错字().