sedの使い方

1. 最後の文字削除

# echo "a1)" | sed -e "s/.\$//"
a1
# echo "a1 b1 c1" | sed -e "s/.\$//"
a1 b1 c

2. sコマンドでデフォルト(/)以外をデリミッタにすることができる

It's a not-so-known fact that sed can use any character as separator for the "s" command. Basically, sed takes whatever follows the "s" as the separator.
So the slash in the middle becomes just a normal character. If I'm interpreting it correctly, your expression:
s=.*/==
could be also be written as:
s/.*\///

and explained as "remove anything before the last slash, including the slash".

これに従いフルパスからファイル名を抜き出す処理を実装できる。
echo "/dir1/dir2/dir3/filename1.dat" | sed 's!^.*/!!'
filename1.dat

例1
/A203F598Z/東京都世田谷区
赤字の部分をsedで削除するには、
sed 's@/[A-Z0-9]/@@g'
とすればよい、sの次の文字がseparatorとなる。

3. ファイル名の日付を削除する

# echo "abc_2020_20200510.txt" | sed "s/[12][90][0-9][0-9][0-9][0-9][0-9][0-9]//g"
abc_2020_.txt
# echo "abc_1999_19990131.txt"  | sed "s/[12][90][0-9][0-9][0-9][0-9][0-9][0-9]//g"
abc_1999_.txt

YYYYMM or YYYYMMDDHHmmss を削除する場合、
# echo "abc_1999_199901_20200331115901.txt"  | sed "s/[12][90][0-9][0-9][0-9][0-9][0-9]*//g"
abc_1999__.txt
注意)[0-9]*
0回以上の繰り返し

4. escape " in sed

以下の置換をする
<LocatorComponent Class="Computer" Name="hostA.fire.com" />

<LocatorComponent Class="Computer" name="abc.com" />

A=<LocatorComponent Class="Computer" Name="hostA.fire.com" />
HOSTNAME=abc.com
とすると、
# echo $A | sed "s/Name=\".*\"/Name=\"${HOSTNAME}\"/g"
# str=$(echo $A | sed "s/Name=\".*\"/Name=\"${HOSTNAME}\"/g")

Windowsでback slashを入力するには
https://316-jp.com/windows-backslash

 5."(ダブルクォーテーション)2つを1つにする

以下のコマンドで実現可能。DataStage External Filter stageでも確認済。

sed -f /tmp/sed_option.txt

cat  /tmp/sed_option.txt

[root@linx:/tmp]$ cat /tmp/sed_option.txt
s/\"\"/\"/g

6.ファイルの指定行を抽出する

6行目、13行目を取得する
 $ sed -n -e 6p -e 13p all.txt
   ToolInstanceID "PJ_ABC_100"
   Identifier "PJOB_TEST_001"
 
6行目から13行目を取得する
 $ sed -n -e 6,13p all.txt

7.後方参照、"で囲まれた文字列を抜き出す

$ cat test.txt
   ToolInstanceID "PJ_ABC_100"
   Identifier "PJOB_TEST_001"
$ cat test.txt | sed -e 's/.*["]\(.*\)["]/\1/g'
PJ_ABC_100
PJOB_TEST_001
 
改行コードを削除して2行を'.'で結合する
$ cat test.txt | sed -e 's/.*["]\(.*\)["]/\1/g' | sed -e "N;s/\r\n/./g"
PJ_ABC_100.PJOB_TEST_001 

8.dsxのプロジェクト名.ジョブ名のリストを表示

DataStageエクスポートファイル(dsx)を複数格納する。
$ list=`ls *.dsx`
$ for file in $list; do sed -n -e 6p -e 13p $file | sed -e 's/.*["]\(.*\)["]/\1/g' | sed -e "N;s/\r\n/./g"; done

 9.crlf→lfの変換

$ cat crlf.txt | sed -e "s/\r//g" >lf.txt 
 
改行コードの確認
$ cat -A crlf.txt
123^M$
456^M$
789^M$
$ xxd crlf.txt  ( binary hex 表示)
00000000: 3132 330d 0a34 3536 0d0a 3738 390d 0a    123..456..789..
 
$ cat -A lf.txt
123$
456$
789$
$ xxd lf.txt
00000000: 3132 330a 3435 360a 3738 390a            123.456.789.

10. 記号を改行コードに変換(MAC)

 1 SELECT&#xD;&#xA;TEST
:%s/&#xD;&#xA;/^M/g
  1 SELECT
  2 TEST

MACでの改行コード^Mの入力は以下である。
Ctrl+Shift+v、Ctrl+Shift+m

コメント

人気の投稿