如何从linux中的数据文件中删除第一列(实际上是行名)?

zar*_*ara 16 linux bash shell

我有数千个列和行的数据文件.我想删除第一列,实际上是行计数器.我在linux中使用了这个命令:

cut -d " " -f 2- input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

但我的输出没有任何改变.有谁知道它为什么不起作用,我该怎么办?

这是我的输入文件的样子:

col1 col2 col3 col4 ...
     1 0 0 0 1
     2 0 1 0 1
     3 0 1 0 0
     4 0 0 0 0 
     5 0 1 1 1 
     6 1 1 1 0
     7 1 0 0 0 
     8 0 0 0 0
     9 1 0 0 0
     10 1 1 1 1
     11 0 0 0 1
    .
    .
    .
Run Code Online (Sandbox Code Playgroud)

我希望我的输出看起来像这样:

col1 col2 col3 col4 ...
0 0 0 1
0 1 0 1
0 1 0 0
0 0 0 0 
0 1 1 1 
1 1 1 0
1 0 0 0 
0 0 0 0
1 0 0 0
1 1 1 1
0 0 0 1
.
.
.
Run Code Online (Sandbox Code Playgroud)

我也试过这个sed命令:

 sed '1d' input.file > output.file
Run Code Online (Sandbox Code Playgroud)

但它会删除第一行而不是第一列.

有人可以指导我吗?

kar*_*kfa 16

惯用的切割会

cut -f2- input > output
Run Code Online (Sandbox Code Playgroud)

如果您的分隔符是制表符("\ t").

或者,只需使用awk魔法(适用于空格和制表符分隔符)

 awk '{$1=""}1' input | awk '{$1=$1}1' > output
Run Code Online (Sandbox Code Playgroud)

第一个awk将删除字段1,但是留下一个分隔符,第二个awk删除分隔符.默认输出分隔符将为空格,如果要更改为制表符,则添加-vOFS="\t"到第二个awk.

更新

根据您更新的输入,问题是将处理切割为多列的初始空间.一种解决方法是在喂食切割之前先将它们取出

sed 's/^ *//' input | cut -d" " -f2- > output
Run Code Online (Sandbox Code Playgroud)

或者使用awk上面的替代方案,也可以在这种情况下使用.


buf*_*uff 13

您可以使用cut--complement选项的命令:

cut -f1 -d" " --complement input.file > output.file
Run Code Online (Sandbox Code Playgroud)

这将输出除第一列之外的所有列.

  • `cut -d' ' -f2- input.file` 和 `cut -f1 -d' ' --complement` 做同样的事情,不需要额外的输入。 (2认同)

小智 6

@Karafka我有CSV文件所以我添加了","分隔符(你可以替换你的

cut -d"," -f2- input.csv  > output.csv
Run Code Online (Sandbox Code Playgroud)

然后,我使用循环遍历目录中的所有文件

# files are in the directory tmp/
for f in tmp/*
do
    name=`basename $f`
    echo "processing file : $name"
    #kepp all column excep the first one of each csv file 

    cut -d"," -f2- $f > new/$name
    #files using the same names are stored in directory new/  
done
Run Code Online (Sandbox Code Playgroud)

  • 为什么你认为分隔符是逗号?输入/输出样本和描述/脚本都没有提到它。 (2认同)
  • 是的,它可能是逗号,但事实并非如此。还有一个单一的输入/输出文件。这可能是另一个问题的正确答案,但我不明白为什么这是*这个*问题的选定答案? (2认同)