首页 > 解决方案 > 从shell中的文件的每一行中删除字符

问题描述

我有一个 shell 脚本,它逐行读取变量的值。我需要从每一行中删除某些字符。

我所拥有的 - $sample_variable -

Data 0 start; 1 ABCD0;2 EFGH0;3 IJKL0;4 MNOP0;5 QRST0;6 end;

我想要的是 -

start
ABCD0
EFGH0
IJKL0
MNOP0
QRST0
end

我写的代码 -

IFS=$';' 
for j in $sample_variable
do  
    j=$j | cut -d ' ' -f3-
    echo $j
    j=${j// /''}
    echo $j
    echo $j >> output.txt
done

我正在将输出写入 txt 文件。但是,该文件被写入 output.txt -

start
1ABCD0
2EFGH0
3IJKL0
4MNOP0
5QRST0
6end

如何删除开头出现的数字?

标签: shellfileksh

解决方案


如果您尝试删除所有数字,我会说您可以尝试使用该tr工具,如下所示:

IFS=$';' for j in $sample_variable do j=$j | cut -d ' ' -f3- echo $j j=${j// /''} echo $j | tr -d [:digit:] echo $j | tr -d [:digit:] >> output.txt done

但是,如果您只想删除初始数字,则需要一个更通用的工具,例如sed,它看起来像:

IFS=$';' for j in $sample_variable do j=$j | cut -d ' ' -f3- echo $j j=${j// /''} echo $j | sed -e 's/^[0-9]\?//' echo $j | sed -e 's/^[0-9]\?//' >> output.txt done


推荐阅读