用于操作现有文本文件的批处理脚本

时间:2014-04-22 09:39:25

标签: shell batch-file

我是编写批处理脚本的新手,忙于下面的示例教程我可以学习一两件事。我真的需要帮助编写批处理脚本以在现有文本文件的中间插入一行文本

例如,给定文件myfile.txt,其内容为:

a
bcd
efg
hjiklmnop
q
rs
t
uvwxyz

命令./put-in-middle.sh "=== === ===" myfile.txt 应该将文件修改为:

a
bcd
efg
hjiklmnop
=== === ===
q
rs
t
uvwxyz

2 个答案:

答案 0 :(得分:1)

@echo off

rem Count the number of lines in the file with FIND
for /F %%a in ('find /C /V "" ^< %2') do set numLines=%%a

rem Get the number of middle line
set /A middle=numLines/2

rem Process all lines, use FINDSTR /N to insert line numbers
for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %2') do (
   rem Echo the original line
   echo/%%b
   rem If the line is the middle one...
   if %%a equ %middle% (
      rem Insert the new line
      echo %~1
   )
)

将以前的批处理文件创建为put-in-middle.bat并以这种方式执行:

put-in-middle "=== === ===" myfile.txt

注意:

  • 以前的程序不会检查错误,例如缺少参数。如果您愿意,可以添加此检查。
  • 如果行为空,则插入命令echo/%%b中的斜杠以避免消息“ECHO已打开”。如果该行可能包含字符串“/?”,则该命令应更改为echo(%%b以避免在这种情况下显示echo帮助(左括号是唯一可以执行该操作的字符)。
  • 如果文件包含批处理特殊字符,例如< > | & ),则echo/%%b命令会失败。在这种情况下,必须添加对文件行的特殊处理。同一点适用于新插入的行。
  • 以前的程序只在屏幕上显示新文件。如果要替换原始文件,必须将输出重定向到辅助文件并在最后替换原始文件:

(for /F "tokens=1* delims=:" %%a in ('findstr /N "^" %2') do (
   . . .
)) > auxiliar.txt
move /Y auxiliar.txt %2

答案 1 :(得分:0)

使用sed并假设偶数行:

sed $(( $(wc input -l | cut -d' ' -f1) / 2))'a=== === ===' input

这是脚本版本put-in-middle.sh

line=$1
file=$2
sed $(( $(wc $file -l | cut -d' ' -f1) / 2))"a$line" $file
相关问题