2

我想编写一个 shell 脚本,它将从标准输入读取文件,删除所有字符串和空行字符,并将输出写入标准输出。该文件如下所示:

#some lines that do not contain <html> in here
<html>a<html>
<tr><html>b</html></tr>
#some lines that do not contain <html> in here
<html>c</html>

因此,输出文件应包含:

#some lines that do not contain <html> in here
a
<tr>b</html></tr>
#some lines that do not contain <html> in here
c</html>

我尝试编写这个 shell 脚本:

read INPUT #read file from std input
tr -d '[:blank:]'
grep "<html>" | sed -r 's/<html>//g'
echo $INPUT

但是这个脚本根本不起作用。任何的想法?谢谢

4

2 回答 2

1

awk 可以轻松做到:

awk '/./ {gsub("<html>","");print}' INPUTFILE

首先,它对至少有一个字符的每一行进行操作(因此空行被丢弃),并用<html>该行上的一个空字符串全局替换“”,然后打印它。

于 2013-03-19T19:54:48.497 回答
1

纯重击:

#!/bin/bash

while read line
do
    #ignore comments
    [[ "$line" = "\#" ]] && continue
    #ignore empty lines
    [[ $line =~ ^$ ]] && continue
    echo ${line//\<html\>/}
done < $1

输出:

$ ./replace.sh input
#some lines that do not contain in here
a
<tr>b</html></tr>
#some lines that do not contain in here
c</html>

纯sed:

sed -e :a -e '/^[^#]/N; s/<html>//; ta' input | sed '/^$/d'
于 2013-03-19T20:03:10.027 回答