5

我需要通过 cron 运行 bash 脚本来更新文件。该文件是一个 .DAT(类似于 csv)并包含管道分隔值。我需要在顶部插入一个标题行。

这是我到目前为止所拥有的:

#!/bin/bash
# Grab the file, make a backup and insert the new line
sed -i.bak 1i"red|blue|green|orange|yellow" thefilename.dat

Exit

但是如何将文件另存为不同的文件名,以便它始终采用 fileA,对其进行编辑,然后将其另存为 fileB

4

3 回答 3

3

你真的把旧的重命名为 xxx.bak 还是你可以保存一个新的副本?

无论哪种方式,只需使用重定向。

sed 1i"red|blue|green|orange|yellow" thefilename.dat > newfile.dat

或者如果你也想要 .bak

sed 1i"红色|蓝色|绿色|橙色|黄色" thefilename.dat > newfile.dat \
&& mv thefilename.dat thefilename.dat.bak`

这将创建您的新文件,然后,仅当 sed 成功完成时,重命名 orig 文件。

于 2013-09-10T23:29:30.107 回答
1

万一有人觉得它有用,这就是我最终要做的......

抓取原始文件,将其转换为所需的文件类型,同时插入一个新的标题行并记录下来。

#!/bin/bash -l
####################################
#
# This script inserts a header row in the file $DAT and resaves the file in a different format
#
####################################

#CONFIG

LOGFILE="$HOME/bash-convert/log-$( date '+%b-%d-%y' ).log"
HOME="/home/rootname"

# grab original file
WKDIR="$HOME/public_html/folder1"
# new location to save
NEWDIR="$HOME/public_html/folder2"

# original file to target
DAT="$WKDIR/original.dat"

# file name and type to convert to
NEW="$NEWDIR/original-converted.csv"


####################################

# insert a new header row
HDR="header-row-1|header-row-2|header-row-2 \r"

# and update the log file
{
echo "---------------------------------------------------------" >> $LOGFILE 2>&1
echo "Timestamp: $(date "+%d-%m-%Y: %T") : Starting work" >> $LOGFILE 2>&1
touch "$LOGFILE" || { echo "Can't create logfile -- Exiting."  && exit 1  ;} >>"$LOGFILE"

# check if file is writable
sudo chmod 755 -R "$NEW"
echo "Creating file \"$NEW\", and setting permissions."
touch "$NEW"  || { 
echo "Can't create file \"$NEW\" -- Operation failed - exiting" && exit 1   ;}

} >>"$LOGFILE" 2>&1

{
echo "Prepending line \"$HDR\" to file $NEW."
{ echo "$HDR" ; cat "$DAT" ;} > "$NEW"

 {   
if [ "$?" -ne "0" ]; then
echo "Something went wrong with the file conversion."
exit 1

else echo "File conversion successful. Operation complete."
fi
}

} >>"$LOGFILE" 2>&1
exit 0
于 2013-09-11T03:28:10.227 回答
0

我发现模式“插入”的两个单引号之间的“i”语法更加清晰。

您可以简单地添加一个标题,并将其保存在不同的文件中:

sed '1i header' file > file2

在你的情况下:

sed '1i red|blue|green|orange|yellow' file > file2

如果您想将其保存在同一个文件中,您可以使用-i选项:

sed -i '1i red|blue|green|orange|yellow' file
于 2020-03-04T11:26:15.453 回答