AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / ubuntu / 问题 / 987138
Accepted
elanozturk
elanozturk
Asked: 2017-12-18 07:37:34 +0800 CST2017-12-18 07:37:34 +0800 CST 2017-12-18 07:37:34 +0800 CST

如何从文件中随机替换文本?

  • 772

如何用另一个文件中的字符串随机替换一个文本文件中的特定字符串?例如:

file1.txt(file has more than 200 lines):
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

file2.txt(file has 10-20 lines):
@adress1.com
@adress2.com
@adress3.com
@adress4.com
@adress5.com

output.txt:
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
command-line
  • 6 6 个回答
  • 2085 Views

6 个回答

  • Voted
  1. janos
    2017-12-18T07:45:44+08:002017-12-18T07:45:44+08:00

    你可以实现这个算法:

    • 将 的内容加载file2.txt到数组中
    • 对于 中的每一行file1.txt:
      • 提取名称部分
      • 获取随机地址
      • 打印格式正确的输出

    像这样:

    mapfile -t addresses < file2.txt
    while IFS='' read -r orig || [[ -n "$orig" ]]; do
        ((index = RANDOM % ${#addresses[@]}))
        name=${orig%%@*}
        echo "$name${addresses[index]}"
    done < file1.txt
    

    (特别感谢@GlennJackman 和@dessert 的改进。)

    • 10
  2. Best Answer
    steeldriver
    2017-12-18T08:07:32+08:002017-12-18T08:07:32+08:00

    如果您真的想要随机选择,那么这是一种使用方法awk:

    awk '
      BEGIN{FS="@"; OFS=""} 
      NR==FNR{a[NR]=$0; n++; next} 
      {$2=a[int(1 + n * rand())]; print}
    ' file2.txt file1.txt
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    

    OTOH,如果您想要地址的随机排列,我建议您使用类似

    paste -d '' <(cut -d'@' -f1 file1.txt) <(sort -R file2.txt)
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    
    • 9
  3. terdon
    2017-12-18T08:08:12+08:002017-12-18T08:08:12+08:00

    您可以使用shuf(您可能需要sudo apt install shuf)来打乱第二个文件的行,然后使用它们来替换:

    $ awk -F'@' 'NR==FNR{a[NR]=$1;next}{print a[FNR]"@"$2} ' file1 <(shuf file2)
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    

    shuf只是随机化其输入行的顺序。那里的awk命令将首先读取 file1 的所有内容(NR==FNR仅在读取第一个文件时为真),并将第二个字段(字段由 定义@,因此这是域)保存在关联数组中a,其值为域和其键是行号。然后,当我们进入下一个文件时,它将简单地打印a为该行号存储的任何内容,以及文件 2 中相同行号的内容。

    请注意,这假设两个文件具有完全相同的行数,并且实际上并不是“随机的”,因为它不允许重复任何内容。但这看起来像你想要的。

    • 5
  4. David Foerster
    2017-12-18T13:54:03+08:002017-12-18T13:54:03+08:00

    Python 2.7 和 3 解决方案

    此解决方案将输入文件每一行中第一次出现的单个任意给定字符串(“needle”)替换为每次从替换字符串列表的行集中随机选择的字符串。

    #!/usr/bin/python
    from __future__ import print_function
    import sys, random
    
    needle = sys.argv[1]
    
    if sys.argv[2] == '-':
        f_replacements = sys.stdin
    else:
        f_replacements = open(sys.argv[2])
    with f_replacements:
        replacements = [l.rstrip('\n') for l in f_replacements]
    if not replacements:
        raise ValueError('No replacement strings given')
    
    if len(sys.argv) <= 3 or sys.argv[3] == '-':
        f_in = sys.stdin
    else:
        f_in = open(sys.argv[3])
    with f_in:
        for s in f_in:
            rep = replacements[random.randrange(len(replacements))]
            print(s.rstrip('\n').replace(needle, rep, 1))
    

    将指针锚定到字符串的开头或结尾或完全使用正则表达式应该几乎是微不足道的。

    用法

    python replace-random.py NEEDLE REPLACEMENTS-FILE [INPUT-FILE]
    

    例子:

    python replace-random.py '@address.com' file2.txt file1.txt
    

    或者

    python replace-random.py '@address.com' file2.txt < file1.txt
    
    • 5
  5. Josh
    2017-12-18T16:32:19+08:002017-12-18T16:32:19+08:00

    这是一种perl方式:

    #!/usr/bin/perl
    use warnings;
    use strict;
    use Tie::File;
    
    tie my @file1,'Tie::File','file1.txt' or die "Can't open file1.txt\n";
    tie my @file2,'Tie::File','file2.txt' or die "Can't open file2.txt\n";
    
    for my $file_index (0..$#file1) {
       my $suffix = $file2[int(rand($#file2+1))];
       $file1[$file_index] =~ s/@.*$/$suffix/;
    }
    
    untie @file1;
    untie @file2;
    
    • 3
  6. SigmaPiEpsilon
    2017-12-18T13:47:19+08:002017-12-18T13:47:19+08:00

    另一个 bash 解决方案。它使用 bash 内置的字符串替换功能。它还假设file2.txt仅包含替换字符串。如果不是,他们可以首先使用过滤grep -o <replace> file2.txt

    和shuf

    #search string
    Search="@address.com"
    for lines in $(grep $Search file1.txt)
    do 
        echo ${lines/$Search/$(shuf file2.txt -n 1)} 
    done
    

    没有shuf(几乎纯bash)

    在这里,我们必须首先创建一个shuf像这样模仿的函数

    bshuf () 
    { 
        nlines=$(( $(wc -l < $1) + 1))
        rand=0
        while [ "$rand" -eq 0 ]; do
            rand=$(( $RANDOM % nlines ))
        done
        echo $(head -n $rand $1 | tail -1)
    }
    

    然后是类似的

    for lines in $(grep $Search file1.txt) 
    do 
        echo ${lines/$Search/$(bshuf file2.txt)}
    done
    

    测试:

    $ for lines in $(grep $Search file1.txt); do echo ${lines/$Search/$(bshuf file2.txt)} ; done
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    [email protected]
    $ 
    
    • 2

相关问题

  • 如何从命令行仅安装安全更新?关于如何管理更新的一些提示

  • 如何从命令行刻录双层 dvd iso

  • 如何从命令行判断机器是否需要重新启动?

  • 文件权限如何工作?文件权限用户和组

  • 如何在 Vim 中启用全彩支持?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何运行 .sh 脚本?

    • 16 个回答
  • Marko Smith

    如何安装 .tar.gz(或 .tar.bz2)文件?

    • 14 个回答
  • Marko Smith

    如何列出所有已安装的软件包

    • 24 个回答
  • Marko Smith

    无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗?

    • 25 个回答
  • Martin Hope
    Flimm 如何在没有 sudo 的情况下使用 docker? 2014-06-07 00:17:43 +0800 CST
  • Martin Hope
    Ivan 如何列出所有已安装的软件包 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    La Ode Adam Saputra 无法锁定管理目录 (/var/lib/dpkg/) 是另一个进程在使用它吗? 2010-11-30 18:12:48 +0800 CST
  • Martin Hope
    David Barry 如何从命令行确定目录(文件夹)的总大小? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher “以下软件包已被保留:”为什么以及如何解决? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford 如何删除 PPA? 2010-07-30 01:09:42 +0800 CST

热门标签

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve