sed はインラインコメントを削除します。

sed はインラインコメントを削除します。

jsファイルからコメントを削除する単純なbashスクリプトがあります。

#!/bin/bash
sed -E '/^[[:blank:]]*(\/\/|#)/d;s/#.*//' $1 >> stripped.js

インラインコメントを除くとほぼ完璧です。

// file-to-be-stripped.js
...
...
const someVar = 'var' // this comment won't be stripped
// this comment will be stripped

インラインコメントを削除するには何がありましたか?

修正する:

本当に奇妙なことは、オンラインbashシェルを使って例を始めましたが、完全に実行されたことです!しかし、まったく同じコードをローカルで実行しても、インラインコードは削除されません! ?なぜ/どのようにこれが起こるのかご存知ですか?私は明らかに何かを見逃しています...非常に奇妙です。

更新されたコードは次のとおりです。

私のスクリプト:Stripper.sh

#!/bin/bash
sed -E -e 's:(\s+(//|#)|^\s*(//|#)).*$::; /^$/d' $1 > "stripped.${1}"

私のテストファイル:test.js

// testies one
const testies = 'two'
console.log(testies) // three
// testies FOUR!?
console.log('Mmmmm toast') // I won't be stripped of my rights!

次に実行します。./stripper.sh test.js出力は次のとおりです。

const testies = 'two'
console.log(testies) // three
console.log('Mmmmm toast') // I won't be stripped of my rights!

まったく同じコードがローカルで実行されますが、sedの行全体が次のようにコメントアウトされる理由についてのアイデアがあります。オンラインbash通訳(残念ながら、私のシェルへの正確なリンクはbit.lyリンクなので共有できません。ここでは明らかに「いいえ」です。)これは期待どおりに機能しますか?

ベストアンサー1

POSIXlyでは、次のようにします。

sed '
  s|[[:blank:]]*//.*||; # remove //comments
  s|[[:blank:]]*#.*||; # remove #comments
  t prune
  b
  :prune
  /./!d; # remove empty lines, but only those that
         # become empty as a result of comment stripping'

GNUを使用すると、sed次のように短縮できます。

sed -E 's@[[:blank:]]*(//|#).*@@;T;/./!d'

#thingsこれは喜んで削除され、//things次のコメントではないことに注意してください。

const url = 'http://stackexchange.com';
x = "foo#bar";

内部引用符を無視#するには//、次のようにします。

perl -ne 'if (/./) {
   s{\s*(?://|#).*|("(?:\\.|[^"])*"|'"'(?:\\\\.|[^'])*'"'|.)}{$1}g;
   print if /./} else {print}'

次のように入力すると:

#blah
// testies one
const testies = 'two';
console.log(testies) // three

const url = 'http://stackexchange.com';
x = "not#a comment";
y = "foo\"bar" # comment
y = 'foo\'bar' # it's a comment

それは以下を提供します:

const testies = 'two';
console.log(testies)

const url = 'http://stackexchange.com';
x = "not#a comment";
y = "foo\"bar"
y = 'foo\'bar'

#(このファイルの実際の言語に適応する必要があるかもしれません。node.jsで始まる最初の行を除いて、JavaScriptがコメントをサポートしているかどうかわかりません#!。)

おすすめ記事