使用分隔符将grep的输出存储到变量中

时间:2018-07-13 11:23:35

标签: shell grep

我有一个带有以下文本的sample.txt文件

abcde
cde
abcdefg
efga
abgd
efghji

我想用bc搜索包含grep bc sample.txt的字符串,并将输出输出到带有定界符的变量(例如##)。我该怎么做?输出应如下所示。

abcde##abcdefg##

3 个答案:

答案 0 :(得分:1)

嗯,一个简单的解决方案:

0

使用tr简单地用'#'替换换行符,然后使用sed用两个'#'替换'#'。

答案 1 :(得分:1)

public static string GenerateBitKey(int letterCount = 44)
    {
        // Get the number of words and letters per word.
        int num_letters = letterCount;
        // Make an array of the letters we will use.
        char[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

        // Make a random number generator.
        Random rand = new Random();

        // Make the words.
        // Make a word.
        string word = "";
        for (int j = 1; j <= num_letters; j++)
        {
            // Pick a random number between 0 and 25
            // to select a letter from the letters array.
            int letter_num = rand.Next(0, letters.Length - 1);

            // Append the letter.
            word += letters[letter_num];
        }
        return word;
    }

将新行转换为#,将1#转换为2 ##

可能有更好的方法,但是效果很好。 。

答案 2 :(得分:0)

您可以将awk与这样的东西配合使用:

OUT=$(awk '/bc/ {printf "%s##",$0};' file)

这会将输出保存在变量$OUT中。

$ awk '/bc/ {printf "%s##",$0};' file

通过搜索/bc/的出现然后添加后缀##来工作,注意使用printf代替print,这是因为{{1} }总是添加和换行,使用print可以避免这种情况,printf %s##将返回整行。