从文本文件中获取一行并进行编辑

时间:2012-01-26 17:15:07

标签: linux bash shell edit

据说我的文本文件中有这一行,格式如下。

"Title:Author:Price:QtyAvailable:QtySold"

我的文本文件的内容如下所示

 Hello World:Andreas:10.50:10:5
 Lord Of The Rings:Duke:50.15:50:20
    (some other records...)

1)用户输入作者和标题。

2)如果程序找到作者+标题,它会要求用户更新任何可用字段(对于本案例,标题,作者,价格等。

3)例如,我想更新Hello World书的价格。

4)我该怎么做才能告诉程序提取Hello World行的内容,并进入10.50以取代本书的价格? (假设书的新价格将由用户的输入决定)

希望得到我的答案。 提前感谢那些帮助过的人!

2 个答案:

答案 0 :(得分:2)

你可以像这样使用带有可变参数的sed:

# book title:author to be searched
BOOK="Hello World:Andreas"

# price to be updated
PRICE=11.25

# search and update with original backed up with .bak extension
sed -i.bak 's/\('"$BOOK"'\):[^:]*:/\1:'"$PRICE"':/' file.txt

<强>解释

如果将shell变量填入sed命令,它将如下所示:

sed 's/\(Hello World:Andreas\):[^:]*:/\1:11.25:/'

<强>匹配

"$BOOK"                 # match literal text i.e. Hello World:Andreas
\($BOOK\)               # group this text to be back referenced later
:                       # match literal :
[^:]*                   # match 0 or more characters until : is found
:                       # match a :

<强>替换

\1                      # group # 1 i.e. Hello World:Andreas
:                       # a literal :
$PRICE                  # fill in the new price
:                       # literal :                   

本质上,这个sed命令是查找文本,其中Hello World:Andreas:后跟某个价格值,然后是另一个:。一旦找到这个模式,它就会用反向引用#1(Hello World:Andreas)替换后跟:,然后将新的价格值和冒号:替换为

编辑:强烈建议您阅读一些sed教程,但根据您的评论,我为您提供了更新数量的命令:

# book title:author to be searched
BOOK="Hello World:Andreas"

# quantity to be updated
QTY=18

# search and update with original backed up with .bak extension
sed 's/^\('"$BOOK"'\):\([^:]*\):[^"]*:/\1:\2:'"$QTY"':/'

答案 1 :(得分:0)

以下是让您入门的内容:

示例脚本:

[jaypal:~/Temp] cat s.sh 
#!/bin/bash

echo "Author?"
read author

echo "Title?"
read title

grep -c "$title:$author" file > /dev/null # Look for a line with matching values

if [ $? == 0 ]; then # If found then offer to change price
    echo "I found the book, Do you want to update price to what?"
    read newprice
    sed -i "s/\($book:$author\):[^:]*:/\1:$newprice:/" file
fi

输入数据:

[jaypal:~/Temp] cat file
Hello World:Andreas:10.50:10:5
Lord Of The Rings:Duke:50.15:50:20

执行:

[jaypal:~/Temp] ./s.sh 
Author? 
Andreas
Title? 
Hello World
I found the book, Do you want to update price to what?
40
[jaypal:~/Temp] cat file
Hello World:Andreas:40:10:5
Lord Of The Rings:Duke:50.15:50:20