2016-10-06 7 views
0

ファイル名のサフィックスを削除する方法はありますか?問題は、接尾辞の長さが異なることです。 filename内の同じ文字列だけが_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のソリューションはありますか?

ありがとうございます。

+0

は申し訳ありませんが、それはタイプミスでした。私はちょうどそれを編集しました。 – Paul

答えて

4

純粋な文字列操作技術を使用して: -

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

Fまたはすべての行は、ファイルが、あなたはあなたがでprintfを変更することによって、新しいファイルに内容を書き込むことができます

# 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 

抽出し、メモリ内のファイルを読み込んで実行することにより、bashで同じことを行うことができますint型ここで

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

sedを提案します。

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

例:

$ for LINE in NAME-code_code2_L001_sufix NAME-code_L001_sufix_sufix2_sufix3 NAME-code_code2_code3_L001_sufix_sufix2_sufix3; do echo "$LINE"|sed 's|\(.*\)_L001.*|\1|';done 
NAME-code_code2 
NAME-code 
NAME-code_code2_code3 
+0

申し訳ありませんが、それはタイプミスでした:-) – Paul

2

あなたはawkの中で、フィールドセパレータとして_L001を使用し、最初のフィールドを印刷することができます。

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

NAME-code_code2 
NAME-code 
NAME-code_code2_code3 
1

として、forループgrepソリューションです:_L001が見られているまで、これは最初から行を出力します。これを行うには

grep -oP '^.*?(?=_L001)' inputfile 
NAME-code_code2 
NAME-code 
NAME-code_code2_code3 
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$> 
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 
関連する問題