5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Cシェル備忘録】連続したスペースを含むテキストの扱い

Posted at

はじめに

連続したスペースを含むテキストファイルを編集するシェルスクリプトを作成する必要が生じた際に、初心者の私が苦肉の策を講じたサンプルコードを掲載したいと思います。

実現したかったこと

各行の桁数が決まっているテキストファイル(以下の例では10桁)を読み込み、特定の桁を置換したファイルを出力する。(便宜上、半角スペースを「-」で表示)
【例】

input.txt
a--bb---cc

 このテキストを

output.txt
a--xx---cc

 に修正(先頭から4,5桁目をbbからxxに置換)。

サンプルコード

あれこれ試す中で、編集時に連続したスペースが1つに集約されたり、あいまいな範囲指定だとエラーが表示されたりしました。最終的に連続したスペースで区切られた文字列を切り出し、置換して再度つなげる際にスペースを再現する荒技で対処しました。

sample.csh
#!/bin/csh

set readStr = "`sed -n 1p input.txt`"   #テキストファイルの1行目を代入

set outStr1 = `echo "${readStr}" | cut -c 1`   #1桁目「a」を代入
set outStr2 = "xx"   #置換用
set outStr3 = `echo "${readStr}" | cut -c 9-10`   #9,10桁目「cc」を代入

set space1 = "`printf "%2s"`"   #2連続スペースを用意
set space2 = "`printf "%3s"`"   #3連続スペースを用意

#文字列とスペースを連結
echo "${outStr1}${space1}${outStr2}${space2}${outStr3}" >> output.txt

おわりに

シェルスクリプトの中でCシェルを採用したのは配列が使用できるためで、実際には今回の処理の中の一部も配列を用いましたが、連続したスペースを配列の要素とするとうまくいかなかったため、上記のようなスクリプトになりました。

似たような処理の実現でお困りの方の手助けとなれば幸いです。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?