删除文件名中的特定字符

时间:2016-10-06 11:46:31

标签: bash awk sed suffix

有没有简单的解决方法如何修剪我的文件名后缀?问题是,我的后缀长度是变化的。文件名中只有相同的字符串是_L001。

参见示例:

NAME-code_code2_L001_sufix
NAME-code_L001_sufix_sufix2_sufix3
NAME-code_code2_code3_L001_sufix_sufix2_sufix3

我需要在_L001之前输出所有内容:

NAME-code_code2
NAME-code
NAME-code_code2_code3

我在考虑做这样的事情(当后缀是固定长度时):

echo NAME-code_code2_L001_sufix | rev | cut -c 12- | rev

但我的后缀长度当然有所不同。有没有bash或awk解决方案?

谢谢。

6 个答案:

答案 0 :(得分:4)

使用纯字符串操作技术: -

$ string="NAME-code_code2_L001_sufix"; printf "%s\n" "${string%_L001*}"
NAME-code_code2

对于文件中的所有行,您可以通过bash执行相同操作,方法是读取内存中的文件并执行提取

# Setting a variable to the contents of a file using 'command-substitution'
$ mystringfile="$(<stringfile)"                 

# Read the new-line de-limited string into a bash-array for per-element operation
$ IFS=$'\n' read -d '' -ra inputArray <<< "$mystringfile"

# Run the sub-string extraction for each entry in the array
$ for eachString in "${inputArray[@]}"; do printf "%s\n" "${eachString%_L001*}"; done

NAME-code_code2
NAME-code
NAME-code_code2_code3

您可以通过修改for循环中的printf将内容写入新文件

printf "%s\n" "${eachString%_L001*}" >> output-file

答案 1 :(得分:2)

您可以在awk中使用_L001作为字段分隔符并打印第一个字段:

awk -F '_L001' '{print $1}' file

NAME-code_code2
NAME-code
NAME-code_code2_code3

答案 2 :(得分:1)

我建议sed

dbms_output.put_line(i || ' is prime');

示例:

sed 's|\(.*\)_L001.*|\1|'

答案 3 :(得分:1)

以下是grep解决方案:这将打印从开始到_L001的行。

grep -oP '^.*?(?=_L001)' inputfile
NAME-code_code2
NAME-code
NAME-code_code2_code3

答案 4 :(得分:1)

许多方法可以做到这一点:

# Here is your Input text.
bash$> cat a.txt
NAME-code_code2_L001_sufix
NAME-code_L001_sufix_sufix2_sufix3
NAME-code_code2_code3_L001_sufix_sufix2_sufix3
bash$>

# Desired output using perl.
bash$> cat a.txt |perl -nle 'if (/^(.+)_L.*$/){print $1}'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>

# Desired output using sed.
bash$> cat a.txt |sed 's#\(.*\)_L001_.*#\1#g'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>

# Desired output using cut
bash$> cat a.txt |cut -f1 -d "L"|sed 's/_$//g'
NAME-code_code2
NAME-code
NAME-code_code2_code3
bash$>

答案 5 :(得分:1)

您也可以使用string substitution, 类似的东西:

for i in NAME-code_code2_L001_sufix NAME-code_L001_sufix_sufix2_sufix3 NAME-code_code2_code3_L001_sufix_sufix2_sufix3
do
    echo ${i%_L001*}
done