【问题标题】:create file from existing file in Linux从 Linux 中的现有文件创建文件
【发布时间】:2018-07-02 05:14:11
【问题描述】:

我在Liunx 有一个文件,里面有很多行。

Contents of the file:

abcdeqroop[
g
;ld

'
d
sksd
;
s'sa;abcdeqroop';kaf
100 gmail eng en101 usa ten
yahoomail dffdd
''

100 200 hotmail and'usfifoi2[[[[[10101
f[
dsl
ks

s'dakd
sd1jz
sdj
sasa;kas

';cxvdl;s;4

;sdljodsl

600 outlookmail 79903083434==13==

我想从这个文件中创建一个新文件,如下所示

gmail eng en101 usa ten
yahoomail dffdd
hotmail and'usfifoi2[[[[[10101
outlookmail 79903083434==13==

Conditions to create the file.

检查任何行是否存在以下字符串gmail, yahoomail, hotmail, outlookmail

If string is not present then delete the file.
If string is present then delete all the characters before it and get the rest of the characters as new line.

我该怎么做?

我已经完成了如下操作

grep -E 'gmail|yahoomail|outlookmail|hotmail' test_file

我得到的输出如下

100 gmail eng en101 usa ten
yahoomail dffdd
100 200 hotmail and'usfifoi2[[[[[10101
600 outlookmail 79903083434==13==

【问题讨论】:

  • 在第一个条件下使用 bash 使用 grep(您可以将 grep 与多个关键字一起使用,如果文件不存在则删除文件),第二个条件 sed 就足够了。这可能会有所帮助:stackoverflow.com/questions/9541867/…
  • @darvark 请用我的尝试检查我的问题的更新部分
  • 使用 grep 和 -L 选项,并检查返回状态,如果单词存在则返回码为 0,否则为 127
  • 请避免"Give me the codez" 问题。另见How much research effort is expected of Stack Overflow users?
  • 你快到了。查看您的 grep -E 输出到 sed 并使用 sed 功能“捕获组”请参阅 sed tutorial 。祝你好运。

标签: linux bash


【解决方案1】:

你可以为它创建一个小脚本,例如:

#!/bin/bash
# -*- coding: utf-8 -*-

OLDIFS=$IFS
IFS=$'\n'
echo -n "Choose the file to read: "; read File
echo -n "Name of the file to be saved: "; read File2
true > $File2

for line in `cat $File`
do
    case "$line" in
    *"hotmail"*) echo -e $line | sed 's/^.*hotmail/hotmail/'  >> $File2;;
    *"yahoo"*) echo -e $line | sed 's/^.*yahoo/yahoo/'  >> $File2;;
    *"gmail"*) echo -e $line | sed 's/^.*gmail/gmail/'  >> $File2;;
    *"outlookmail"*) echo -e $line | sed 's/^.*outlookmail/outlookmail/'  >> $File2;;
    esac

done
IFS=$OLDIFS

希望对你有所帮助

【讨论】:

【解决方案2】:

您可以使用以下命令 -

第一部分 - 从整个文件中查找邮件别名

egrep -r "*mail*" temp >> temp1

第二部分 - 删除多余的字符

sed -re "s@(.*)\s(.*mail)(.*)@\2\3@" temp1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多