简体   繁体   English

带sed和随机数的Shell脚本

[英]Shell Script With sed and Random number

How to make a shell script that receives one or more text files and removes from them whitespaces and blanklines. 如何制作一个shell脚本来接收一个或多个文本文件,并从中删除空格和空白行。 After that new files will have a random 2-digit number in front of them. 之后,新文件将在其前面有一个随机的2位数字。
For example File1.txt generates File1_56.txt 例如File1.txt生成File1_56.txt

Tried this: 试过这个:

#!/bin/bash
for file in "$*"; do
sed -e '/^$/d;s/[[:blank:]]//g' $* >> "$*_$$.txt"
done 

But when I give 2 files as input script merges them into one single file, when I want for each file a separate one. 但是,当我给2个文件作为输入脚本时,它们会将它们合并为一个文件,而当我想要为每个文件分配一个单独的文件时。

Try: 尝试:

#!/bin/bash
for file in "$@"; do
    sed -e '/^$/d;s/[[:blank:]]//g' "$file" >> "${file%.txt}_$$.txt"
done 

Notes 笔记

  1. To loop over each argument without word splitting or other hazards, use for file in "$@" not for file in "$*" 要遍历每个自变量而不会出现单词拆分或其他危险,请使用for file in "$@" for file in "$*"而不是for file in "$*"

  2. To run the sed command on one file instead of all, specify "$file" as the file, not $* . 要在一个文件而不是全部文件上运行sed命令,请指定"$file"作为文件,而不是$*

  3. To save the output to the correct file, use "${file%.txt}_$$.txt" where ${file%.txt} is an example of suffix removal : it removes the final .txt from the file name. 要将输出保存到正确的文件中,请使用"${file%.txt}_$$.txt" ,其中${file%.txt}后缀删除的示例:它将从文件名中删除最终的.txt

  4. $$ is the process ID. $$是进程ID。 The title says mentions a "random" number. 标题说有一个“随机”数字。 If you want a random number, replace $$ with $RANDOM . 如果您想要一个随机数,请将$$替换为$RANDOM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM